package com.zoe.onelink.mybatis.autoconfigure.check;

import com.zoe.onelink.mybatis.properties.OnelinkMybatisPluginProperties;
import com.zoe.onelink.plugin.check.AbstractEnvironmentChecker;
import com.zoe.onelink.plugin.check.model.PropertyCheckResult;
import com.zoe.onelink.util.StrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-22
 */
public class MybatisEnvironmentChecker extends AbstractEnvironmentChecker {

    @Override
    protected List<PropertyCheckResult<?>> doCheck() {
        OnelinkMybatisPluginProperties mybatisPluginProperties = this.getBean(OnelinkMybatisPluginProperties.class);
        OnelinkMybatisPluginProperties.QueryLimit queryLimit = mybatisPluginProperties.getQueryLimit();
        List<PropertyCheckResult<?>> propertyCheckResults = new ArrayList<>();
        if (!mybatisPluginProperties.isEnableQueryLimit()) {
            String msg = StrUtil.format("未开启Mybatis查询返回行数拦截器,可能存在全表查询问题");
            PropertyCheckResult<Boolean> queryLimitCheckResult = new PropertyCheckResult<Boolean>()
                    .setPropKey(OnelinkMybatisPluginProperties.PREFIX + ".enableQueryLimit")
                    .setPropValue(false)
                    .setLevel(PropertyCheckResult.Level.DANGER)
                    .setMessage(msg);
            propertyCheckResults.add(queryLimitCheckResult);

        } else if (queryLimit.getMaxResultRows() == -1 || queryLimit.getMaxResultRows() > 10000) {
            String msg = StrUtil.format("Mybatis查询返回行数最大限制大于10000,可能存在OOM风险,建议该值低于10000");
            PropertyCheckResult<Integer> maxResultRowsCheckResult = new PropertyCheckResult<Integer>()
                    .setPropKey(OnelinkMybatisPluginProperties.PREFIX + ".queryLimit.maxResultRows")
                    .setPropValue(queryLimit.getMaxResultRows())
                    .setLevel(PropertyCheckResult.Level.DANGER)
                    .setMessage(msg);
            propertyCheckResults.add(maxResultRowsCheckResult);

        }
        return propertyCheckResults;
    }

}
